import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'

const service = axios.create({
  // baseURL: 'http://10.0.27.61:8081',
  baseURL: 'http://admin-wjsg.nex-i.cn',
  timeout: 10000
})

// 请求拦截器
service.interceptors.request.use((config) => {
  const token = getToken()

  if (token) {
    config.headers.token = token
  }

  return config
}, (error) => {
  return Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(async response => {
  if (response.data instanceof Blob) return response.data
  const { rows, msg, code, data } = response.data
  if (code === 10000) {
    const obj = {
      data: data || rows,
      total: response.data?.total || ''
    }
    return obj
  } else if (code === 20001) {
    Message({ type: 'warning', message: 'token超时了' })
    await store.dispatch('user/logout')
    return Promise.reject(new Error(msg))
  } else {
    Message({ type: 'error', message: msg })
    return Promise.reject(new Error(msg))
  }
}, async(error) => {
  if (error.response.status === 20001) {
    Message({ type: 'warning', message: 'token超时了' })
    await store.dispatch('user/logout')
    return Promise.reject(error)
  }
  Message({ type: 'error', message: error.msg })
  return Promise.reject(error)
})

export default service
